package com.yxsk.relay.job.admin.config.registry.security;

import com.yxsk.relay.job.admin.data.entity.JobApps;
import com.yxsk.relay.job.admin.data.service.JobAppsService;
import com.yxsk.relay.job.component.admin.exception.registry.RelayJobRegistryException;
import com.yxsk.relay.job.component.admin.registry.security.SecurityChecker;
import com.yxsk.relay.job.component.common.vo.SlaveInfo;
import lombok.AllArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Author 11376
 * @CreaTime 2019/7/2 9:34
 * @Description 白名单IP安全检查
 */
@AllArgsConstructor
public class SpecificIpSecurityChecker implements SecurityChecker {

    private SpecificIpGetter ipGetter;

    private JobAppsService appsService;

    @Override
    public void check(SlaveInfo slaveInfo, String token) throws RelayJobRegistryException {
        if (ipGetter != null) {
            List<String> trustIp = ipGetter.getTrustIp(slaveInfo.getAppName());
            // 信任的 IP 为空或者不在信任 ip 列表中
            if (CollectionUtils.isEmpty(trustIp) || !trustIp.contains(slaveInfo.getEndpoint().getHost())) {
                throw new RelayJobRegistryException("Untrusted ip.");
            }
        }
    }

    @Override
    public boolean isCheck(SlaveInfo slaveInfo, String token) {
        JobApps apps = this.appsService.findByAppName(slaveInfo.getAppName());
        return apps == null || JobApps.AuthType.IP.getType().equals(apps.getAuthType());
    }

    public interface SpecificIpGetter {

        List<String> getTrustIp(String appName);

    }

    @AllArgsConstructor
    public static class DefaultSpecificIpGetter implements SpecificIpGetter {

        private JobAppsService appsService;

        @Override
        public List<String> getTrustIp(String appName) {
            JobApps apps = appsService.findByAppName(appName);
            return apps == null || StringUtils.isEmpty(apps.getAuthIps()) ? Collections.emptyList() : Arrays.asList(apps.getAuthIps().split(","));
        }
    }

}